package net.mof.manual.meta

import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.TypeName
import net.mof.manual.MarkedClass
import net.mof.manual.MarkedClassInfo
import net.mof.manual.Utils.JSONObject_ClassName
import net.mof.manual.Utils.jsonObject
import net.mof.manual.Utils.manualClassName
import net.mof.manual.Utils.upFirstChar

/**
 *
 *  对象类型
 *
 * Created by LiYueHui on 2020/2/2.
 */
class JsonMarkFieldMetaInfo : BaseFieldMetaInfo() {

    var jsonMarkField: MarkedClass? = null

    fun getClassName(): ClassName? {
        return ClassName.get(jsonMarkField?.packageName,
                jsonMarkField?.markedClassInfo?.getClassName())
    }

    override fun instanceTypeName(): TypeName = JSONObject_ClassName;

    override fun optField(): String = "JSONObject"

    override fun jsonToTypeGet(builder: CodeBlock.Builder, markedClassInfo: MarkedClassInfo) {
        builder.beginControlFlow("if (\$L != null && \$L.length() > 0)", value,
                value)
                .addStatement(
                        "\$L.set\$L(\$T.jsonToType(\$L.toString(), \$T.class))",
                        markedClassInfo.getFileName()?.toLowerCase(),
                        upFirstChar(filedName()), manualClassName, value,
                        getClassName()).endControlFlow()
    }

    override fun typeToJsonObjectPut(builder: CodeBlock.Builder?, param: String?) {
        builder?.addStatement("\$T \$L = \$L.get\$L()", getClassName(), value,
                param, upFirstChar(filedName()))?.beginControlFlow("if (\$L != null)", value)?.addStatement("\$L.put(\$S,\$T.typeToJSONObject(\$L))", jsonObject,
                value, manualClassName, value)?.endControlFlow()
    }


}